package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Kirito
 * @description: 解析mapper.xml文件
 * @date 2020/03/25
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 利用dom4j解析mapper.xml文件，封装成MapperStatement对象
     *
     * @param inputStream InputStream
     * @throws DocumentException DocumentException
     */
    public void parseMapper(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> selectElements = rootElement.selectNodes("//select");
        List<Element> insertElements = rootElement.selectNodes("//insert");
        List<Element> updateElements = rootElement.selectNodes("//update");
        List<Element> deleteElements = rootElement.selectNodes("//delete");
        List<Element> elements = new ArrayList<>();
        elements.addAll(selectElements);
        elements.addAll(insertElements);
        elements.addAll(updateElements);
        elements.addAll(deleteElements);
        for (Element selectElement : elements) {
            String id = selectElement.attributeValue("id");
            String resultType = selectElement.attributeValue("resultType");
            String parameterType = selectElement.attributeValue("parameterType");
            String sql = selectElement.getTextTrim();

            // 封装MappedStatement
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);

            // 生成唯一的statementId
            String mappedStatementId = namespace + "." + id;
            configuration.getMappedStatementMap().put(mappedStatementId, mappedStatement);
        }

    }
}
